<template>
  <div class="user-profile">
    <el-card class="profile-card">
      <template #header>
        <div class="card-header">
          <span>个人信息</span>
          <el-button type="primary" @click="handleEdit">编辑</el-button>
        </div>
      </template>
      <div class="profile-content">
        <div class="avatar-container">
          <el-avatar :size="100" :src="userInfo.avatar" />
          <div v-if="isEdit" class="avatar-uploader">
            <el-button type="primary" size="small" @click="showCropper">更换头像</el-button>
          </div>
        </div>
        
        <el-form
          ref="profileForm"
          :model="form"
          :rules="rules"
          label-width="100px"
          :disabled="!isEdit"
        >
          <el-form-item label="用户名">
            <el-input v-model="userInfo.userName" disabled />
          </el-form-item>
          <el-form-item label="昵称" prop="nickName">
            <el-input v-model="form.nickName" placeholder="请输入昵称" />
          </el-form-item>
          <el-form-item label="手机号码" prop="phonenumber">
            <el-input v-model="form.phonenumber" placeholder="请输入手机号码" />
          </el-form-item>
          <el-form-item label="邮箱" prop="email">
            <el-input v-model="form.email" placeholder="请输入邮箱" />
          </el-form-item>
          <el-form-item v-if="isEdit">
            <el-button type="primary" @click="submitForm">保存</el-button>
            <el-button @click="cancelEdit">取消</el-button>
          </el-form-item>
        </el-form>
      </div>
    </el-card>

    <el-card class="password-card">
      <template #header>
        <div class="card-header">
          <span>修改密码</span>
        </div>
      </template>
      <el-form
        ref="pwdForm"
        :model="pwdForm"
        :rules="pwdRules"
        label-width="100px"
      >
        <el-form-item label="旧密码" prop="oldPassword">
          <el-input
            v-model="pwdForm.oldPassword"
            type="password"
            placeholder="请输入旧密码"
            show-password
          />
        </el-form-item>
        <el-form-item label="新密码" prop="newPassword">
          <el-input
            v-model="pwdForm.newPassword"
            type="password"
            placeholder="请输入新密码"
            show-password
          />
        </el-form-item>
        <el-form-item label="确认密码" prop="confirmPassword">
          <el-input
            v-model="pwdForm.confirmPassword"
            type="password"
            placeholder="请确认新密码"
            show-password
          />
        </el-form-item>
        <el-form-item>
          <el-button type="primary" @click="updatePwd">修改密码</el-button>
          <el-button @click="resetPwdForm">重置</el-button>
        </el-form-item>
      </el-form>
    </el-card>

    <el-dialog
      title="更换头像"
      v-model="cropperVisible"
      width="800px"
      append-to-body
      @opened="onCropperOpened"
      @close="onCropperClosed"
    >
      <el-row>
        <el-col :xs="24" :md="12" :style="{ height: '350px' }">
          <vue-cropper
            ref="cropperRef"
            :img="cropperOptions.img"
            :info="true"
            :autoCrop="true"
            :autoCropWidth="200"
            :autoCropHeight="200"
            :fixedBox="true"
            outputType="png"
            @realTime="onPreview"
          />
        </el-col>
        <el-col :xs="24" :md="12" :style="{ height: '350px' }">
          <div class="preview-container">
            <img :src="cropperOptions.preview.url" :style="cropperOptions.preview.img" />
          </div>
        </el-col>
      </el-row>
      <div class="cropper-control">
        <el-upload
          class="upload-demo"
          action="#"
          :show-file-list="false"
          :auto-upload="false"
          :on-change="onFileChange"
          accept="image/*"
        >
          <el-button type="primary">
            选择图片
            <el-icon class="el-icon--right"><Upload /></el-icon>
          </el-button>
        </el-upload>
        <el-button-group>
          <el-button icon="Plus" @click="zoom(0.1)" />
          <el-button icon="Minus" @click="zoom(-0.1)" />
          <el-button icon="RefreshLeft" @click="rotate('left')" />
          <el-button icon="RefreshRight" @click="rotate('right')" />
        </el-button-group>
        <el-button type="primary" @click="handleAvatarUpload">确 定</el-button>
      </div>
    </el-dialog>
  </div>
</template>

<script setup>
import { ref, reactive, watch, onMounted } from 'vue'
import { ElMessage } from 'element-plus'
import useUserStore from '@/store/modules/user'
import { getToken } from '@/utils/auth'
import { updateUserProfile, updateUserPwd, uploadAvatar } from '@/api/user/profile'
import 'vue-cropper/dist/index.css'
import { VueCropper } from 'vue-cropper'

const userStore = useUserStore()
const userInfo = ref({})
const isEdit = ref(false)

// 表单数据
const form = ref({
  nickName: '',
  phonenumber: '',
  email: ''
})

// 表单校验规则
const rules = {
  nickName: [
    { required: true, message: '昵称不能为空', trigger: 'blur' }
  ],
  phonenumber: [
    { pattern: /^1[3-9]\d{9}$/, message: '请输入正确的手机号码', trigger: 'blur' }
  ],
  email: [
    { type: 'email', message: '请输入正确的邮箱地址', trigger: 'blur' }
  ]
}

// 密码表单数据
const pwdForm = ref({
  oldPassword: '',
  newPassword: '',
  confirmPassword: ''
})

// 密码表单校验规则
const pwdRules = {
  oldPassword: [
    { required: true, message: '旧密码不能为空', trigger: 'blur' }
  ],
  newPassword: [
    { required: true, message: '新密码不能为空', trigger: 'blur' },
    { min: 6, max: 20, message: '密码长度必须在6到20个字符之间', trigger: 'blur' }
  ],
  confirmPassword: [
    { required: true, message: '确认密码不能为空', trigger: 'blur' },
    {
      validator: (rule, value, callback) => {
        if (value !== pwdForm.value.newPassword) {
          callback(new Error('两次输入的密码不一致'))
        } else {
          callback()
        }
      },
      trigger: 'blur'
    }
  ]
}

// 裁剪相关
const cropperVisible = ref(false)
const cropperRef = ref(null)
const cropperOptions = reactive({
  img: '',
  preview: {
    url: '',
    img: {}
  }
})

// 上传相关
const uploadAvatarUrl = import.meta.env.VITE_APP_BASE_API + '/user/profile/avatar'
const headers = {
  Authorization: 'Bearer ' + getToken()
}

// 初始化用户信息
const initUserInfo = () => {
  const user = userStore.user
  if (user) {
    userInfo.value = user
    form.value = {
      nickName: user.nickName || '',
      phonenumber: user.phonenumber || '',
      email: user.email || ''
    }
  }
}

// 监听用户信息变化
watch(() => userStore.user, (newVal) => {
  if (newVal) {
    userInfo.value = newVal
    if (!isEdit.value) {
      form.value = {
        nickName: newVal.nickName || '',
        phonenumber: newVal.phonenumber || '',
        email: newVal.email || ''
      }
    }
  }
}, { immediate: true })

// 编辑按钮点击
const handleEdit = () => {
  isEdit.value = true
  form.value = {
    nickName: userInfo.value.nickName || '',
    phonenumber: userInfo.value.phonenumber || '',
    email: userInfo.value.email || ''
  }
}

// 取消编辑
const cancelEdit = () => {
  isEdit.value = false
  form.value = {
    nickName: userInfo.value.nickName || '',
    phonenumber: userInfo.value.phonenumber || '',
    email: userInfo.value.email || ''
  }
}

// 提交表单
const submitForm = async () => {
  try {
    const res = await updateUserProfile(form.value)
    if (res.code === 200) {
      ElMessage.success('个人信息修改成功')
      // 更新用户信息
      userStore.getInfo()
      isEdit.value = false
    } else {
      ElMessage.error(res.msg || '修改失败')
    }
  } catch (error) {
    console.error('修改个人信息失败:', error)
    ElMessage.error('修改失败')
  }
}

// 修改密码
const updatePwd = async () => {
  try {
    const res = await updateUserPwd(pwdForm.value.oldPassword, pwdForm.value.newPassword)
    if (res.code === 200) {
      ElMessage.success('密码修改成功')
      resetPwdForm()
    } else {
      ElMessage.error(res.msg || '修改失败')
    }
  } catch (error) {
    console.error('修改密码失败:', error)
    ElMessage.error('修改失败')
  }
}

// 重置密码表单
const resetPwdForm = () => {
  pwdForm.value = {
    oldPassword: '',
    newPassword: '',
    confirmPassword: ''
  }
}

// 显示裁剪对话框
const showCropper = () => {
  cropperVisible.value = true
}

// 对话框打开时的处理
const onCropperOpened = () => {
  cropperOptions.img = userInfo.value.avatar || ''
}

// 对话框关闭时的处理
const onCropperClosed = () => {
  cropperOptions.img = ''
  cropperOptions.preview = { url: '', img: {} }
}

// 文件选择处理
const onFileChange = (file) => {
  const isImage = file.raw.type.startsWith('image/')
  const isLt2M = file.raw.size / 1024 / 1024 < 2

  if (!isImage) {
    ElMessage.error('只能上传图片文件!')
    return
  }
  if (!isLt2M) {
    ElMessage.error('图片大小不能超过2MB!')
    return
  }

  const reader = new FileReader()
  reader.readAsDataURL(file.raw)
  reader.onload = () => {
    cropperOptions.img = reader.result
  }
}

// 实时预览
const onPreview = (data) => {
  cropperOptions.preview = data
}

// 缩放
const zoom = (ratio) => {
  cropperRef.value?.changeScale(ratio)
}

// 旋转
const rotate = (direction) => {
  if (direction === 'left') {
    cropperRef.value?.rotateLeft()
  } else {
    cropperRef.value?.rotateRight()
  }
}

// 上传头像
const handleAvatarUpload = () => {
  cropperRef.value?.getCropBlob(async (blob) => {
    const formData = new FormData()
    formData.append('avatarfile', blob, 'avatar.png')

    try {
      const response = await uploadAvatar(formData)
      console.log('头像上传响应:', response)
      
      if (response.code === 200) {
        // 关闭裁剪对话框
        cropperVisible.value = false
        
        // 构建完整的头像URL
        const baseApi = import.meta.env.VITE_APP_BASE_API.replace(/\/+$/, '')
        const avatarUrl = baseApi + response.imgUrl
        
        // 更新 userStore 中的头像
        userStore.avatar = avatarUrl
        
        // 更新本地显示
        userInfo.value = {
          ...userInfo.value,
          avatar: avatarUrl
        }
        
        ElMessage.success('头像更新成功')
      } else {
        ElMessage.error(response.msg || '上传失败')
      }
    } catch (error) {
      console.error('上传头像失败:', error)
      ElMessage.error('上传失败')
    }
  })
}

// 监听用户信息变化
watch(() => userStore.avatar, (newVal) => {
  if (newVal) {
    userInfo.value.avatar = newVal
  }
}, { immediate: true })

// 组件挂载时初始化数据
onMounted(() => {
  initUserInfo()
})
</script>

<style lang="scss" scoped>
.user-profile {
  padding: 20px;
  
  .profile-card,
  .password-card {
    margin-bottom: 20px;
    
    .card-header {
      display: flex;
      justify-content: space-between;
      align-items: center;
    }
  }
  
  .profile-content {
    .avatar-container {
      text-align: center;
      margin-bottom: 20px;
      
      .avatar-uploader {
        margin-top: 10px;
      }
    }
  }

  .preview-container {
    width: 100%;
    height: 100%;
    overflow: hidden;
    display: flex;
    align-items: center;
    justify-content: center;
    background: #f5f7fa;
  }

  .cropper-control {
    margin-top: 20px;
    display: flex;
    justify-content: space-between;
    align-items: center;
  }
}
</style> 